#include "main.h"
#include "Timer.h"
#include "myapplication.h"

float detectzero(float num)
{
	// move the 5 decimal digits we want to before the decimal point
//	float temp = ( num * pow(10.0f, ZEROTOLERANCEDIGITS) );
	float temp = ( num * 100000 ); // because pow() is slow

	// make temp the numbers we don't want, then move them back to their original positions
//	temp = ( temp - (int) temp ) / pow(10.0f, ZEROTOLERANCEDIGITS);
	temp = ( temp - (int) temp ) / 100000;

	// and then we remove those numbers from the original number(num)
	return num - temp;
}

void changeSize(int w, int h) {
	myApplication::getInstance()->changeSize(w,h);
}

void renderScene(void) {
	myApplication* app = myApplication::getInstance();

	float deltaTime = float(timeGetTime() - app->timelastcall);
	if (deltaTime > 1000 / app->frequency)
	{
		// Calculate the framerate
		app->calculateFPS();

		app->timelastcall = timeGetTime();
		app->Update(deltaTime / app->frequency);
		app->renderScene();
		return;
	}
}

void inputKey(int key, int x, int y) {
	myApplication::getInstance()->inputKey(key,x,y);
}

void KeyboardDown(unsigned char key, int x, int y){
	myApplication::getInstance()->KeyboardDown(key,x,y);
}

void KeyboardUp(unsigned char key, int x, int y){
	myApplication::getInstance()->KeyboardUp(key,x,y);
}

void MouseMove(int x, int y){
	myApplication::getInstance()->MouseMove(x,y);
}

void MouseClick(int button, int state, int x, int y){
	myApplication::getInstance()->MouseClick(button, state, x, y);
}

void CleanUpUponExit(void)
{
	myApplication::getInstance()->drop();
}

int main(int argc, char **argv )
{
	LuaScript *lua = LuaScript::getInstance();
	lua->LoadFile("../init.lua");

	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
	glutInitWindowPosition(250,50);
	glutInitWindowSize(lua->getVari("window_height"),lua->getVari("window_width"));
	glutCreateWindow(lua->getVars("window_title"));
	if(lua->getVarb("enable_fullscreen")) glutFullScreen();
	glewInit();

	glutDisplayFunc(renderScene);
	glutIdleFunc(renderScene);
	glutReshapeFunc(changeSize);
	glutSpecialFunc(inputKey);
	glutKeyboardFunc(KeyboardDown);
	glutKeyboardUpFunc(KeyboardUp);
	glutMotionFunc(MouseMove);
	glutPassiveMotionFunc(MouseMove);
	glutMouseFunc(MouseClick);// for mouse click

	atexit(CleanUpUponExit);

	if (myApplication::getInstance()->Init() == true)
	{
		glutMainLoop();
	}
	else
	{
		printf("Error Initialising Program\n");
		return 1;
	}

	return 0;
}